package com.qf.rbac2202.controller;

import com.baomidou.kaptcha.Kaptcha;
import com.qf.rbac2202.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    Kaptcha kaptcha;

    @PostMapping("/sys/login")
    public R login(String username, String password, String captcha){

        //1. 验证码处理
        try {
             kaptcha.validate(captcha);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("验证码错了");
        }

        //2. 用户身份信息比对
        final Subject subject = SecurityUtils.getSubject();

        // shiro的登录方法
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.error("用户名或者密码错误");
        }

        return R.ok();

    }

}
